<template>
	<div class="div1">
		<el-backtop target=".div1"></el-backtop>
		<!-- 头部 -->

		<Head :data="searchList" style="background: #fff;"></Head>
		<!-- 中部内容 -->
		<div style="background: #F6F5F7;">
			<div class="tong">
				<div class="content-top">
					<div class="save-address">{{$t('placeOrder.Consignee')}} <span class="xintian" @click="tianjia()">{{$t('placeOrder.NewlyFilledDeliveryAddress')}}</span></div>
					<div v-if="checkAddress == true">
						<div class="user-msg" style="display: flex" v-for="(item, index) in editAddress" :key="index"
							@click="selectAddress(item)">
							<div class="name">
								<img v-if="item.select" src="../../../static/images/order/23.png" alt="">
								<div class="user-name">{{ item.provinces }} ({{ item.consignee }}{{$t('shopCartOrder.receive')}})</div>
							</div>
							<div class="address">{{ item.detail }} （ {{ $t('login.MobilePhoneNumber') }}：{{ item.mobile }} ）</div>
						</div>
					</div>
					<div v-if="checkAddress == false">
						{{ $t('placeOrder.ThereIsNoAddress') }}
					</div>
					<img src="../../assets/index/caitiao.png" class="caitiao" />
				</div>
			</div>

			<div class="tong three">
				<div class="content-top1">
					<div class="save-address">{{ $t('placeOrder.commodity') }}</div>
					<div>
						<el-table :data="tableData" style="width: 100%">
							<el-table-column prop="date" :label="$t('placeOrder.GoodsInformation')" width="350">
								<template slot-scope="scope">
									<div>
										<img :src="scope.row.coverImg" class="imgs" />
										<div class="rights">
											<div class="title">{{ scope.row.title }}</div>
											<div class="guige">{{ $t('placeOrder.specifications') }}:{{ checkString }}
											</div>
										</div>
									</div>
								</template>
							</el-table-column>
							<el-table-column v-if="relationId != 'null'" prop="memberPrice"
								:label="$t('placeOrder.unitPrice') + '(' + $t('placeOrder.yuan') + ')'"></el-table-column>
							<el-table-column v-else prop="price"
								:label="$t('placeOrder.unitPrice') + '(' + $t('placeOrder.yuan') + ')'"></el-table-column>
							<el-table-column prop="number" :label="$t('goodsDet.quantity')">
								<template slot-scope="scope">
									<div>
										<el-input-number size="mini" v-model="scope.row.number"
											@change="handleChange(scope.row, scope.$index)" :min="1" step-strictly>
										</el-input-number>
									</div>
								</template>
							</el-table-column>
							<el-table-column prop="zsp"
								:label="$t('placeOrder.money') + '(' + $t('placeOrder.yuan') + ')'">
								<template slot-scope="scope">
									<div v-if="relationId != 'null'">{{ (scope.row.number *
										scope.row.memberPrice).toFixed(2)}}</div>
									<div v-if="relationId == 'null'">{{ (scope.row.number * scope.row.price).toFixed(2)
										}}</div>
								</template>
							</el-table-column>
							<el-table-column prop="postagePrice"
								:label="$t('placeOrder.transportation') + '(' + $t('placeOrder.yuan') + ')'">
							</el-table-column>
						</el-table>
						<div class="liuyan">{{ $t('placeOrder.toTheSeller') }}：<input class="ly"
								style="width: 300px;height: 40px;" v-model="liuyan"
								:placeholder="$t('placeOrder.YouCan')"></div>
						<div class="liuyan">{{ $t('placeOrder.coupon') }}：

							<el-select v-model="value"
								:placeholder="$t('placeOrder.PleaseSelect') + $t('placeOrder.coupon')"
								@change='selCoupon' style="width: 300px;">
								<el-option v-for="item in couponList" :key="item.value" :label="item.couponName"
									:value="item.couponIssueId">
								</el-option>
							</el-select>

							<span class="zjeS">-{{ couponMoney }}{{ DollarSignValue }}</span>
						</div>
						<div class="zje">{{ $t('placeOrder.amountOfGoods') }}：<span class="zjeS">{{ zongjineSp
								}}{{ DollarSignValue }}</span>
						</div>
						<div class="zje">{{ $t('placeOrder.freight') }}：<span class="zjeS">{{ zongjineYf
								}}{{ DollarSignValue }}</span></div>
						<div class="right">
							<div class="rightT">
								<div class="zje">{{ $t('placeOrder.Actualpayment') }}：<span class="zjeS">{{ zongjine
										}}{{ DollarSignValue }}</span></div>
								<div class="psdz">{{ $t('placeOrder.SendTo') }}：<span class="dz">{{ provinces }}
										{{ detail }}</span></div>
								<div class="shr">{{ $t('placeOrder.consignee') }}：{{ consignee }} {{ mobile }}</div>
							</div>
							<button class="tijiao" @click="goPay()">{{ $t('placeOrder.SubmitOrder') }}</button>
						</div>
					</div>
				</div>
			</div>
		</div>
		<!-- 底部 -->
		<Foots></Foots>
	</div>
</template>

<script>
import Head from '@/components/head.vue'
import Foots from '@/components/foots.vue'
import goodsItem from "../../components/goods-item";
import { Loading } from "element-ui";

export default {
	components: {
		Head,
		Foots,
		goodsItem
	},
	data() {
		return {
			page: 1,
			searchList: ['粽子', '防晒霜', '洗衣液', '蚊香液', '抽纸', '零食'],
			tableData: [],
			liuyan: '',
			zongjine: 0,
			zongjineSp: 0,
			zongjineYf: 0,
			checkString: '', //规格
			numberMoney: '', //单价
			number: 1, //购买数量
			editAddress: {},
			checkAddress: false,
			detail: '',
			consignee: '',
			mobile: '',
			provinces: '',
			isExpress: 1,
			list: {},
			skuId: 0,
			commissionPrice: 0,
			orderId: 0,//订单id
			relationId: window.localStorage.getItem('relationId'),	//邀请码
			title: '',
			couponList: [],	//优惠卷列表
			couponMoney: 0,
			userCouponsId: '',
			value: '',
			addressId: '',
		}
	},
	mounted() {
		this.checkString = this.$route.query.checkString
		// this.dataSelect()
		// this.getAddressList();
		this.executeRequests()
		this.getCouponList()
	},
	computed: {
		DollarSignValue() {
			// let dollar=this.$store.state.currencyInfo.figure
			let dollar = this.getDollarSign()
			return dollar
		}
	},
	methods: {
		// 在确认获取地址和获取商品详情的请求完成之后再调用查询运费请求
		// async executeRequests() {
		// 	const results = await Promise.all([this.dataSelect(), this.getAddressList()]);
		// 	console.log('aaa------请求完成', results);
		// 	this.getMeteringAll();
		// },
		// 获取货币符号
		getDollarSign() {
			let dollar = this.$store.state.currencyInfo.figure
			return dollar
		},
		async executeRequests() {
			try {
				const [response1, response2] = await Promise.all([
					this.dataSelect(),
					this.getAddressList(),
				]);

				// 在这里，你可以访问response1和response2中的数据
				console.log('Data from first request:', response1);
				console.log('Data from second request:', response2);

				// 现在调用第三个请求
				const response3 = await this.getMeteringAll();
				console.log('Data from third request:', response3);

				// 在这里，你可以根据需要使用response3中的数据来更新你的组件状态或执行其他操作
			} catch (error) {
				// 处理任何在请求过程中发生的错误
				console.error('Error fetching data:', error);
			}
		},
		selCoupon(e) {
			this.couponList.forEach(res => {
				if (res.couponIssueId == e) {
					this.couponMoney = res.lessMoney
					this.userCouponsId = res.couponUserId
				}
			})
			this.jisuan()
		},
		getCouponList() {
			let goodsId = this.$route.query.id
			let userId = this.$cookie.get('userId');
			this.$http({
				url: this.$http.adornUrl('selfCouponUser/useList'),
				method: 'get',
				params: this.$http.adornParams({
					'goodsId': goodsId,
					'userId': userId
				})
			}).then(({ data }) => {
				if (data.status == 0) {
					this.couponList = data.data
				}
			})
		},
		// 添加地址
		tianjia() {
			this.$router.push({
				path: '/order?select=address'
			})
		},
		// 修改地址
		xiugai(dzId) {
			this.$router.push({
				path: '/order?select=address'
			})
		},
		handleChange(row, index) {
			// this.tableData[index].zsp = Number(row.numberMoney) * row.number
			// this.list.zsp = Number(row.numberMoney) * row.number
			// this.jisuan()
			this.getMeteringAll()
		},
		jisuan() {
			console.log('aaa',this.relationId)
			var tableData = this.tableData
			var zyf = 0
			var zsp = 0
			for (var i in tableData) {
				if (tableData[i].postagePrice) {
					zyf = zyf + Number(tableData[i].postagePrice)
				}
				if (this.relationId != 'null') {
					this.tableData[i].zsp = (Number(tableData[i].memberPrice) * Number(tableData[i].number)).toFixed(2)
					zsp = zsp + (Number(tableData[i].memberPrice) * Number(tableData[i].number)).toFixed(2) * 1
				} else {
					this.tableData[i].zsp = (Number(tableData[i].price) * Number(tableData[i].number)).toFixed(2)
					zsp = zsp + (Number(tableData[i].price) * Number(tableData[i].number)).toFixed(2) * 1
				}
			}
			this.list = this.tableData[0]
			this.zongjineSp = zsp.toFixed(2)
			this.zongjineYf = zyf.toFixed(2)
			this.zongjine = (this.zongjineYf * 1 + this.zongjineSp * 1).toFixed(2)
		},
		// 获取商品详情
		dataSelect() {
			let loadingInstance = Loading.service({
				lock: true,
				text: '加载中……',
				background: 'rgba(0, 0, 0, 0.7)'
			});
			let goodsId = this.$route.query.id
			this.title = this.$route.query.title
			let url = ''
			if (this.title == '拼团购') {
				url = this.$http.adornUrl('/selfGroup/find')
			} else {
				url = this.$http.adornUrl('/goods/find')
			}
			return this.$http({
				url: url,
				method: 'get',
				params: this.$http.adornParams({
					'id': goodsId
				})
			}).then(({ data }) => {
				this.$nextTick(() => {
					loadingInstance.close();
				})
				this.tableData = []
				data.data.number = this.$route.query.number
				data.data.checkString = this.$route.query.checkString
				data.data.sku.forEach(e => {
					if (e.detailJson === this.checkString) {
						data.data.memberPrice = e.memberPrice;
						data.data.price = e.skuPrice;
					}
				})
				this.tableData.push(data.data)
				this.list = data.data

				this.jisuan()
			})
		},
		//获取地址列表
		getAddressList() {
			let userId = this.$cookie.get('userId');
			return this.$http({
				url: this.$http.adornUrl('/address/findByUserId'),
				method: 'get',
				params: this.$http.adornParams({
					'userId': userId
				})
			}).then(({ data }) => {
				if (data.status == 0) {
					if (data.data) {
						data.data.forEach(res => {
							// this.provinces = res.provinces;
							// this.detail = res.detail;
							// this.consignee = res.consignee;
							// this.mobile = res.mobile;
							if (res.isDefault) {
								res.select = 1
								this.provinces = res.provinces;
								this.detail = res.detail;
								this.consignee = res.consignee;
								this.mobile = res.mobile;
								this.addressId = res.id;
							} else {
								res.select = 0
								this.provinces = data.data[0].provinces
								this.detail = data.data[0].detail
								this.consignee = data.data[0].consignee
								this.mobile = data.data[0].mobile
								this.addressId = data.data[0].id
							}
						})
						this.editAddress = data.data
						this.checkAddress = true;
					} else {
						this.checkAddress = false;
					}
				} else {
					this.checkAddress = false;
				}
			})
		},
		//选择地址
		selectAddress(e) {
			this.editAddress.forEach(res => {
				if (res.id == e.id) {
					res.select = 1
					this.provinces = res.provinces;
					this.detail = res.detail;
					this.consignee = res.consignee;
					this.mobile = res.mobile;
					this.getMeteringAll()
				} else {
					res.select = 0
				}
			})
		},
		// 支付订单
		goPay() {
			if (this.editAddress.length == 0) {
				this.$notify({
					title: '提示',
					message: '请设置收货地址信息',
					type: 'warning'
				});
				return;
			}
			const loading = this.$loading({
				lock: true,
				text: '订单生成中···',
				spinner: 'el-icon-loading',
				background: 'rgba(0, 0, 0, 0.7)'
			});
			let userId = this.$cookie.get('userId');
			if (this.skuId === 0) {
				this.skuId = this.list.sku[0].id;
			}

			let orderType = '1'; //1普通订单 2拼团 3秒杀
			let type = '';
			let status = '';
			let secKillId = '';
			let groupId = '';
			let goodsId = '';
			let isExpress = '';
			let commissionPrice = '';
			let storeId = '';
			let storeName = '';
			let merchantId = '';
			// console.log(this.list)
			if (this.title === '拼团购') {
				orderType = '2';
				status = '9';
				type = this.list.goods.type.id;
				groupId = this.list.id;
				goodsId = this.list.goodsId;
				storeId = this.list.store ? this.list.store.storeId : '';
				storeName = this.list.store ? this.list.store.storeName : '';
				merchantId = this.list.merchantId;
				isExpress = '1';
				commissionPrice = this.list.price * this.list.commissionPrice;
			} else if (this.title === 'miaosha') {
				orderType = '3';
				status = '1';
				type = this.list.goods.type.id;
				secKillId = this.list.secKillId;
				groupId = this.list.secKillId;
				goodsId = this.list.goodsId;
				storeId = this.list.store ? this.list.store.storeId : '';
				storeName = this.list.store ? this.list.store.storeName : '';
				merchantId = this.list.merchantId;
				isExpress = '1';
				commissionPrice = this.list.price * this.list.commissionPrice;
			} else if (this.className === 'jifen') {
				orderType = '4';
				status = '1';
				type = '';
				goodsId = this.list.id;
				isExpress = this.list.isExpress;
			} else {
				status = '1';
				type = this.list.type.id;
				goodsId = this.list.id;
				isExpress = this.list.isExpress;
				commissionPrice = this.list.price * this.list.commissionPrice;
				storeId = this.list.store ? this.list.store.storeId : '';
				storeName = this.list.store ? this.list.store.storeName : '';
				merchantId = this.list.merchantId;
			}
			this.groupPinkId = this.$route.query.groupPinkId
			console.log(this.list)
			/*let data = {
				userId: userId,
				status: status,
				consignee: this.consignee,
				mobile: this.mobile,
				provinces: this.provinces,
				detail: this.detail,
				type: type,
				secKillId: secKillId,
				groupPinkId: this.groupPinkId,
				orderType: orderType,
				title: this.list.title,
				groupId: groupId,
				couponMoney: '', //这个是优惠券金额，替换了descrition的值描述
				userCouponsId: '',
				goodsId: goodsId,
				img: this.list.coverImg,
				isExpress: isExpress,
				descrition: this.liuyan,
				skuId: this.skuId?this.skuId:this.list.sku[0].id,
				price:this.relationId != 'null'? this.list.memberPrice:this.list.price,
				number: this.list.number,
				postagePrice: this.list.postagePrice,
				payMoney: this.zongjine,
				relationId: this.relationId,	//邀请码,
				detailJson: this.checkString,
				commissionPrice: this.list.memberPrice*this.list.commissionPrice,
				userByinvitationId: '',
			}*/
			this.relationId=localStorage.getItem('relationId')
			let aaa=this.relationId ? this.list.memberPrice : this.list.price
			let data = {
				userId: userId,
				status: status,
				consignee: this.consignee,
				mobile: this.mobile,
				provinces: this.provinces,
				detail: this.detail,
				type: type,
				secKillId: secKillId,
				groupPinkId: this.groupPinkId,
				orderType: orderType,

				storeId: storeId,
				storeName: storeName,

				merchantId: merchantId,
				title: this.list.title,
				groupId: groupId,
				couponMoney: this.couponMoney, //这个是优惠券金额，替换了descrition的值描述
				userCouponsId: this.couponUserId,
				goodsId: goodsId,
				img: this.list.coverImg,
				isExpress: isExpress,
				descrition: this.descrition,
				skuId: this.skuId ? this.skuId : this.list.sku[0].id,
				price: this.relationId ? this.list.memberPrice : this.list.price,
				number: this.list.number,
				postagePrice: this.list.postagePrice,
				payMoney: this.zongjine,
				relationId: this.userByinvitationId,
				detailJson: this.checkString,
				commissionPrice: commissionPrice,
				storeMoney: this.list.price - (this.list.price * this.list.commissionPrice)
			}

			this.$http({
				url: this.$http.adornUrl('/orders/save'),
				method: 'post',
				data: this.$http.adornData(data)
			}).then(res => {
				loading.close();
				if (res.status == 200 && res.data.data) {
					console.log(res.data.data)
					this.$router.push({
						path: '/payment?money=' + res.data.data.payMoney + '&payNum=' + res.data.data.payNum + '&id=' + res.data.data.id
					});
				} else {
					console.log(res.data.msg)
					this.$message({
						type: 'error',
						message: res.data.msg
					});
				}
			});
		},
		// 关闭弹框
		handleClose(done) {
			this.dialogVisible = false
		},
		// 获取运费
		getMeteringAll() {
			let loadingInstance = Loading.service({
				lock: true,
				text: '加载中……',
				background: 'rgba(0, 0, 0, 0.7)'
			});
			let data = []
			let _that = this
			console.log('aaaa------在请求', this.tableData)
			this.tableData.forEach((item) => {
				data.push({
					addressId: _that.addressId,
					goodId: this.$route.query.id,
					sum: item.number
				})
			})
			this.$http({
				url: this.$http.adornUrl('/selfMetering/meteringAll'),
				method: 'post',
				data: this.$http.adornData(data),
			}).then(res => {
				this.$nextTick(() => {
					loadingInstance.close();
				})
				if (res.data.status == 0) {
					let priceFei = res.data.data.data
					this.priceFeiList = priceFei
					let dataObjList = []
					if (this.tableData.length > 0) {
						dataObjList = this.tableData
					} else {
						dataObjList = JSON.parse(window.localStorage.getItem('shopCartOrderList'))
					}
					for (let i = 0; i < this.priceFeiList.length; i++) {
						let itemObj = this.priceFeiList[i]
						for (let g = 0; g < dataObjList.length; g++) {
							let itemObjY = dataObjList[g]
							if (itemObj.id == itemObjY.id) {
								itemObjY.postagePrice = itemObj.postagePrice
							}
						}
					}
					this.tableData = dataObjList
					this.jisuan()
				}
			})
		},

	}
}
</script>

<style scoped>
.div1 {
	height: 100vh;
	overflow-x: hidden;
}


/* 第一部分 */
.tong {
	width: 1200px;
	margin: 0 auto;
	margin-top: 15px;
}

.three {
	margin-bottom: 80px;
}

.content-top {
	/* width: 880px; */
	padding: 20px 20px 0 20px;
	border-radius: 6px;
	background: #fff !important;
}

.content-top1 {
	/* width: 880px; */
	padding: 20px;
	border-radius: 6px;
	background: #fff !important;
}

.save-address {
	color: #333333;
	font-weight: 700;
	font-size: 18px;
	position: relative;
}

.xintian {
	position: absolute;
	right: 0;
	display: inline-block;
	font-size: 12px;
	color: #5293FF;
	font-weight: 500;
}

.user-msg {
	margin: 20px 0;
}

.name {
	position: relative;
	text-align: center;
	line-height: 34px;
}

.name>img {
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 34px;
}

.user-name {
	margin: 0 8px;
	font-width: 700;
	font-size: 16px;
}

.address {
	line-height: 34px;
	margin-left: 20px;
	color: #999999;
	font-size: 16px;
}

.updata-address {
	font-size: 14px;
	color: #d0a182;
	/*margin-top: 20px;*/
}

.caitiao {
	width: 100%;
}

.imgs {
	width: 80px;
	height: 80px;
	float: left;
}

.rights {
	margin-left: 90px;
}

.title {
	word-break: break-all;
	text-overflow: ellipsis;
	overflow: hidden;
	display: -webkit-box;
	-webkit-line-clamp: 2;
	-webkit-box-orient: vertical;
}

.guige {
	margin-top: 6px;
	color: #999;
	font-size: 14px;
}

.liuyan {
	font-size: 13px;
	color: #333;
	margin: 30px 0;
}

.ly {
	margin-left: 10px;
	line-height: 25px;
	height: 25px;
	border: 1px solid #DDDDDD;
	width: 300px;
	padding: 0 15px;
	font-size: 12px;
}

.zje {
	font-size: 14px;
	line-height: 24px;
}

.zjeS {
	color: #EA7408;
	font-weight: 600;
	display: inline-block;
	font-size: 18px;
}

.right {
	text-align: right;
	margin-top: 10px;
}

.rightT {
	width: 40%;
	border: 1px solid #EA7408;
	padding: 20px;
	margin-left: 60%;
	box-sizing: border-box;
}

.psdz {
	margin-top: 20px;
	color: #333;
	font-size: 14px;

}

.dz {
	color: #999999;
}

.shr {
	margin-top: 10px;
	color: #333;
	font-size: 14px;
}

.tijiao {
	margin-top: 20px;
	width: 180px;
	height: 50px;
	line-height: 50px;
	color: #fff;
	background: #EA7408;
	border: 1px solid #EA7408;
	font-size: 15px;

}
</style>
